package com.example.spring.demo.config.strategy;

import com.example.spring.demo.common.SpringContext;
import com.example.spring.demo.config.properties.MyShardingRuleProperty;
import com.example.spring.demo.config.MyShardingUtil;
import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

import java.util.Collection;

/**
 * @author liangchao
 * 11/18/18 9:23 PM
 */
public class MyShardingTableAlgorithm implements PreciseShardingAlgorithm<Integer> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> shardingValue) {
        System.out.println(SpringContext.getBean(MyShardingRuleProperty.class));
        for (String targetName : availableTargetNames) {
            String[] splits = targetName.split("_");
            int no = Integer.parseInt(splits[splits.length - 1]);
            if (no == MyShardingUtil.getTableNo(availableTargetNames.size(),shardingValue.getValue())) {
                return targetName;
            }
        }
        return null;
    }
}
